from rest_framework.response import Response
from utils.viewsets import *
from utils.mixins import *
from apps.HttpTestcase.core.utils import get_version
from apps.HttpTestcase.models import Testcases
from apps.HttpTestcase.serializers.testcases import TestcaseModeSerializer, TestcaseListSerializer
from rest_framework.views import APIView
from rest_framework.generics import DestroyAPIView
from apps.HttpTestcase.models import Interfaces
from apps.CeleryTimedTask.HttpTestcase.testcases_task import batch_exec_testcase
from apps.HttpTestcase.models import Envs
from apps.HttpTestcase.core.http_dlient import HttpSession
from apps.HttpTestcase.core.testcase_debug import HttpTestcaseDebug
from apps.HttpTestcase.models import Testsuite2Testcase
from apps.HttpTestcase.filters.testcase import TestcaseFilters
from utils.response import SuccessResponse


class TestcaseListViewSet(ReadOnlyModelViewSet):
    """
    列表
    """
    queryset = Testcases.objects.filter(is_delete=False)
    serializer_class = TestcaseListSerializer
    filter_class = TestcaseFilters
    filter_fields = ['id', 'name']
    # permission_classes = [permissions.IsAuthenticated]
    perms_map = {'get': '*'}


class TestcasesViewSet(DestroyModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = Testcases.objects.filter(is_delete=False)
    serializer_class = TestcaseModeSerializer
    # 指定过滤引擎
    # filter_fields = [DjangoFilterBackend]
    filter_fields = ['id', 'name']
    # 指定权限类
    # permission_classes = [permissions.IsAuthenticated]
    perms_map = {'get': '*', 'post': 'testcase_create',
                 'put': 'testcase_update', 'delete': 'testcase_delete'}

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()  # 逻辑删除


class TestcaseDebugAPIView(APIView):
    """
    用例调试
    """
    perms_map = {'post': 'testcase_debug'}

    def post(self, request, *args, **kwargs):
        data = request.data
        env_id = data.get('env_id')
        testcase = data.get('testcase')
        name = testcase.get('name')
        api_id = testcase.get('api')
        headers = testcase.get('headers')
        request_data = testcase.get('request_data')
        request_data_type = testcase.get('request_data_type')
        expect_result = testcase.get('expect_result')

        api = Interfaces.objects.filter(id=api_id, is_delete=False).first()
        method = api.method

        env = Envs.objects.filter(id=env_id, is_delete=False).first()
        envs_url = env.base_url

        base_url = testcase.get('url')
        if base_url.startswith('http') or base_url.startswith('https'):
            pass
        else:
            base_url = envs_url + base_url

        http_session = HttpSession()

        http_debug = None
        if request_data_type == "Json":
            http_debug = HttpTestcaseDebug(http_session=http_session, name=name, url=base_url, method=method,
                                           headers=headers,
                                           request_data_type=request_data_type,
                                           json_data=request_data, expect_result=expect_result)
        elif request_data_type == "Form Data":
            http_debug = HttpTestcaseDebug(http_session=http_session, name=name, url=base_url, method=method,
                                           headers=headers,
                                           request_data_type=request_data_type,
                                           form_data=request_data, expect_result=expect_result)

        elif request_data_type == 'Params':
            http_debug = HttpTestcaseDebug(http_session=http_session, name=name, url=base_url, method=method,
                                           headers=headers,
                                           request_data_type=request_data_type,
                                           params_data=request_data, expect_result=expect_result)

        testcase_result = http_debug.debug()
        testcase_result.update({
            "api": api.id,
            "api_name": api.name,
            "testcase": testcase.get('id'),
            "testcase_name": testcase.get('name'),
            "request_data_type": request_data_type,
            'is_periodictask': False
        })
        return SuccessResponse(data={'data': testcase_result}, msg='调试成功！')


class TestcaseBatchAPIView(APIView):
    """
    用例批量执行
    """
    perms_map = {'post': 'testcase_batch'}

    def post(self, request, *args, **kwargs):
        data = request.data
        testcases = data.get('testcases')
        version = get_version()

        # 异步执行
        # batch_exec_testcase.delay(testcases=testcases, version=version)
        batch_exec_testcase.delay(testcases=testcases, version=version)

        return SuccessResponse(data=None, msg='程序正在后台运行中,请稍后查看结果……！')


class TestcasesBatchDelete(DestroyAPIView):
    perms_map = {'delete': 'testcase_delete'}

    def delete(self, request, *args, **kwargs):
        data = request.data
        associated = data.get('associated')
        testcase_list = []
        for item in data.get('data'):
            testcase_list.append(item.get('id'))
        if associated:
            Testcases.objects.filter(id__in=testcase_list).update(is_delete=True)
            Testsuite2Testcase.objects.filter(testcase_id__in=testcase_list).delete()
        else:
            Testcases.objects.filter(id__in=testcase_list).exclude(id__in=Testsuite2Testcase.objects.filter(testcase_id__in=testcase_list).values('testcase_id')).update(is_delete=True)
        return SuccessResponse(data=None, msg='删除成功！')
        # return Response(200, None, '删除成功！')
